package com.example.test4

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.example.test4.model.User
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*

class AmendActivity : AppCompatActivity() {
    private lateinit var user: User
    private lateinit var imagephoto: ImageView  // 拍照预览的ImageView
    private val REQUEST_IMAGE_CAPTURE = 1       // 拍照请求码

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_amend)

        // 获取从首界面传递过来的User对象
        user = intent.getParcelableExtra("user") ?: User()

        // 初始化拍照预览控件
        imagephoto = findViewById(R.id.imageView2)

        // 初始化界面数据
        initViews()

        // 初始化拍照按钮点击事件
        val takephotobutton = findViewById<Button>(R.id.button2)
        takephotobutton.setOnClickListener {
            dispatchTakePictureIntent()
        }

        // 保存按钮点击事件
        findViewById<Button>(R.id.button_save).setOnClickListener {
            updateUserFromViews()  // 更新用户信息
            val intent = Intent()
            intent.putExtra("updatedUser", user)  // 回传更新后的User对象
            setResult(RESULT_OK, intent)
            finish()  // 关闭当前界面
        }
    }

    // 初始化控件，显示原始数据
    private fun initViews() {
        // 显示用户信息
        findViewById<EditText>(R.id.editTextText_name).setText(user.name)
        findViewById<EditText>(R.id.editTextText_phone).setText(user.phone)
        findViewById<EditText>(R.id.editTextText2).setText(user.mail)

        // 初始化性别单选按钮
        if (user.gender == "男") {
            findViewById<RadioButton>(R.id.radio_man).isChecked = true
        } else {
            findViewById<RadioButton>(R.id.radio_woman).isChecked = true
        }

        // 初始化爱好复选框（假设用逗号分隔）
        val hobbies = user.hobbies.split(",")
        findViewById<CheckBox>(R.id.check_travel).isChecked = hobbies.contains("旅游")
        findViewById<CheckBox>(R.id.check_reading).isChecked = hobbies.contains("阅读")
        findViewById<CheckBox>(R.id.check_gaming).isChecked = hobbies.contains("游戏")
        findViewById<CheckBox>(R.id.check_shopping).isChecked = hobbies.contains("购物")

        // 显示已保存的照片（如果有）
        if (user.photoPath != null) {
            val photoFile = File(user.photoPath)
            if (photoFile.exists()) {
                imagephoto.setImageURI(android.net.Uri.fromFile(photoFile))
            }
        }
    }

    // 将控件数据更新到User对象
    private fun updateUserFromViews() {
        user.name = findViewById<EditText>(R.id.editTextText_name).text.toString()
        user.phone = findViewById<EditText>(R.id.editTextText_phone).text.toString()
        user.mail = findViewById<EditText>(R.id.editTextText2).text.toString()

        // 获取性别
        user.gender = if (findViewById<RadioButton>(R.id.radio_man).isChecked) {
            "男"
        } else {
            "女"
        }

        // 获取爱好（拼接选中的复选框文本）
        val hobbies = mutableListOf<String>()
        if (findViewById<CheckBox>(R.id.check_travel).isChecked) hobbies.add("旅游")
        if (findViewById<CheckBox>(R.id.check_reading).isChecked) hobbies.add("阅读")
        if (findViewById<CheckBox>(R.id.check_gaming).isChecked) hobbies.add("游戏")
        if (findViewById<CheckBox>(R.id.check_shopping).isChecked) hobbies.add("购物")
        user.hobbies = hobbies.joinToString(",")
    }

    // 调起相机拍照
    @SuppressLint("QueryPermissionsNeeded")
    private fun dispatchTakePictureIntent() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)

        }
    }


    // 处理拍照结果
    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            // 获取拍照的 bitmap
            val imageBitmap = data?.extras?.get("data") as Bitmap
            // 显示在界面上
            imagephoto.setImageBitmap(imageBitmap)
            // 保存图片到存储并记录路径到User对象
            user.photoPath = saveImageToStorage(imageBitmap)
        }
    }

    // 保存图片到应用私有目录并返回路径
    private fun saveImageToStorage(bitmap: Bitmap): String? {
        return try {
            // 创建唯一的图片文件名
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val imageFileName = "JPEG_${timeStamp}_"
            // 获取应用私有图片目录
            val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            // 创建临时文件
            val imageFile = File.createTempFile(
                imageFileName,  // 文件名前缀
                ".jpg",         // 文件后缀
                storageDir      // 存储目录
            )

            // 将bitmap写入文件
            val fos = FileOutputStream(imageFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)
            fos.flush()
            fos.close()

            // 返回文件绝对路径
            imageFile.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show()
            null
        }
    }
}